package jfconfig;

/**
 * Created : May 17, 2012
 *
 * @author pquiring
 */

import javax.swing.*;
import javax.swing.table.*;

import javaforce.*;

public class PrintersPanel extends javax.swing.JPanel {

  /**
   * Creates new form PrintersPanel
   */
  public PrintersPanel() {
    initComponents();
    model = (DefaultTableModel)printers.getModel();
    listPrinters();
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jToolBar1 = new javax.swing.JToolBar();
    back = new javax.swing.JButton();
    viewJobs = new javax.swing.JButton();
    addPrinter = new javax.swing.JButton();
    deletePrinter = new javax.swing.JButton();
    setDefault = new javax.swing.JButton();
    enable = new javax.swing.JButton();
    configCups = new javax.swing.JButton();
    jScrollPane2 = new javax.swing.JScrollPane();
    printers = new javax.swing.JTable();

    jToolBar1.setFloatable(false);
    jToolBar1.setRollover(true);

    back.setText("< Back");
    back.setFocusable(false);
    back.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    back.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    back.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        backActionPerformed(evt);
      }
    });
    jToolBar1.add(back);

    viewJobs.setText("View Jobs");
    viewJobs.setFocusable(false);
    viewJobs.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    viewJobs.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    viewJobs.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        viewJobsActionPerformed(evt);
      }
    });
    jToolBar1.add(viewJobs);

    addPrinter.setText("Add Printer");
    addPrinter.setFocusable(false);
    addPrinter.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    addPrinter.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    addPrinter.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        addPrinterActionPerformed(evt);
      }
    });
    jToolBar1.add(addPrinter);

    deletePrinter.setText("Delete Printer");
    deletePrinter.setFocusable(false);
    deletePrinter.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    deletePrinter.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    deletePrinter.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        deletePrinterActionPerformed(evt);
      }
    });
    jToolBar1.add(deletePrinter);

    setDefault.setText("Set Default");
    setDefault.setFocusable(false);
    setDefault.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    setDefault.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    setDefault.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        setDefaultActionPerformed(evt);
      }
    });
    jToolBar1.add(setDefault);

    enable.setText("Enable/Disable");
    enable.setFocusable(false);
    enable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    enable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    enable.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        enableActionPerformed(evt);
      }
    });
    jToolBar1.add(enable);

    configCups.setText("CUPS Admin");
    configCups.setFocusable(false);
    configCups.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    configCups.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    configCups.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        configCupsActionPerformed(evt);
      }
    });
    jToolBar1.add(configCups);

    printers.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "Name", "Default", "Enabled"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.String.class, java.lang.String.class, java.lang.String.class
      };
      boolean[] canEdit = new boolean [] {
        false, false, false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    jScrollPane2.setViewportView(printers);
    if (printers.getColumnModel().getColumnCount() > 0) {
      printers.getColumnModel().getColumn(1).setPreferredWidth(25);
      printers.getColumnModel().getColumn(2).setPreferredWidth(25);
    }

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jScrollPane2)
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE)
        .addContainerGap())
    );
  }// </editor-fold>//GEN-END:initComponents

  private void backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backActionPerformed
    ConfigApp.This.setPanel(new MainPanel());
  }//GEN-LAST:event_backActionPerformed

  private void configCupsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configCupsActionPerformed
    try { Runtime.getRuntime().exec(new String[] {"x-www-browser","http://localhost:631/admin"}); } catch (Exception e) {}
  }//GEN-LAST:event_configCupsActionPerformed

  private void viewJobsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewJobsActionPerformed
    int row = printers.getSelectedRow();
    if (row == -1) return;
    String pname = (String)printers.getValueAt(row, 0);
    PrinterJobsDialog dialog = new PrinterJobsDialog(null, true, pname);
    dialog.setVisible(true);
  }//GEN-LAST:event_viewJobsActionPerformed

  private void addPrinterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPrinterActionPerformed
    addPrinter();
  }//GEN-LAST:event_addPrinterActionPerformed

  private void deletePrinterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deletePrinterActionPerformed
    deletePrinter();
  }//GEN-LAST:event_deletePrinterActionPerformed

  private void setDefaultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setDefaultActionPerformed
    setDefault();
  }//GEN-LAST:event_setDefaultActionPerformed

  private void enableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enableActionPerformed
    toggle();
  }//GEN-LAST:event_enableActionPerformed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton addPrinter;
  private javax.swing.JButton back;
  private javax.swing.JButton configCups;
  private javax.swing.JButton deletePrinter;
  private javax.swing.JButton enable;
  private javax.swing.JScrollPane jScrollPane2;
  private javax.swing.JToolBar jToolBar1;
  private javax.swing.JTable printers;
  private javax.swing.JButton setDefault;
  private javax.swing.JButton viewJobs;
  // End of variables declaration//GEN-END:variables

  private DefaultTableModel model;

  private void listPrinters() {
    model.setRowCount(0);
    ShellProcess sp = new ShellProcess();
    String output = sp.run(new String[] {"lpstat", "-p", "-d"}, false);
    //printer $NAME disabled since ...
    //printer $NAME is idle. enabled since ...
    //printer $NAME is printing ... ???
    String lns[] = output.split("\n");
    String def = lns[lns.length-1];
    int idx = def.indexOf(":");
    if (idx == -1) {
      def = "none";
    } else {
      def = def.substring(idx+1).trim();
    }
    for(int a=0;a<lns.length-1;a++) {
      if (lns[a].startsWith("\t")) continue;
      String f[] = lns[a].split(" ");
      if (f.length < 3) continue;
      boolean enabled = false;
      for(int b=2;b<f.length;b++) {
        if (f[b].equals("enabled")) enabled = true;
      }
      model.addRow(new Object[] {f[1], f[1].equals(def) ? "Default" : "", "" + enabled});
    }
  }

  private void addPrinter() {
    PrintersAddDialog dialog = new PrintersAddDialog(null, true);
    dialog.setVisible(true);
    listPrinters();
  }

  private void deletePrinter() {
    int row = printers.getSelectedRow();
    if (row == -1) return;
    String pname = (String)printers.getValueAt(row, 0);
    ShellProcess sp = new ShellProcess();
    String output = sp.run(new String[] {"sudo", "lpadmin", "-x", pname}, false);
    if (sp.getErrorLevel() != 0) {
      JFAWT.showError("Error", "Unable to delete printer:\n"+output);
    }
    listPrinters();
  }

  private void setDefault() {
    int row = printers.getSelectedRow();
    if (row == -1) return;
    String pname = (String)printers.getValueAt(row, 0);
    ShellProcess sp = new ShellProcess();
    String output = sp.run(new String[] {"lpadmin", "-d", pname}, false);
    if (sp.getErrorLevel() != 0) {
      JFAWT.showError("Error", "Unable to set default printer:\n"+output);
    }
    listPrinters();
  }

  private void toggle() {
    int row = printers.getSelectedRow();
    if (row == -1) return;
    String pname = (String)printers.getValueAt(row, 0);
    String state = (String)printers.getValueAt(row, 2);
    ShellProcess sp = new ShellProcess();
    String output1 = sp.run(new String[] {"cups" + (state.equals("true") ? "disable" : "enable"), pname}, false);
    String output2 = sp.run(new String[] {"cups" + (state.equals("true") ? "reject" : "accept"), pname}, false);
    listPrinters();
  }
}
